
package uestc.bitman.edxapp.units;

import uestc.bitman.edxapp.EdxAppConfigurations;
import uestc.bitman.edxapp.player.PlayerJavaScriptExtra;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class VideoPlayerWebView extends WebView {

    private String mVideoTitle;

    private String mVideoUrl;

    private String mVideoTrackUrl;

    public VideoPlayerWebView(Context context) {
        super(context);
        init(context);
    }

    public VideoPlayerWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public VideoPlayerWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void init(Context context) {
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        addJavascriptInterface(new VideoBlockJavaScriptExtra(context), "jso");
    }

    public String getVideoTitle() {
        return mVideoTitle;
    }

    public void setVideoTitle(String mVideoTitle) {
        this.mVideoTitle = mVideoTitle;
    }

    public String getVideoUrl() {
        return mVideoUrl;
    }

    public void setVideoUrl(String mVideoUrl) {
        this.mVideoUrl = mVideoUrl;
    }

    public String getVideoTrackUrl() {
        return mVideoTrackUrl;
    }

    public void setVideoTrackUrl(String mVideoTrackUrl) {
        this.mVideoTrackUrl = mVideoTrackUrl;
    }

    public void playVideo() {
        loadUrl(EdxAppConfigurations.LOCAL_PLAYER_URL);
    }

    class VideoBlockJavaScriptExtra extends PlayerJavaScriptExtra {

        public VideoBlockJavaScriptExtra(Context cxt) {
            super(cxt);
        }

        @JavascriptInterface
        @Override
        public String getVideoUrl() {
            return mVideoUrl;
        }

        @JavascriptInterface
        @Override
        public String getTrackUrl() {
            return mVideoTrackUrl;
        }

        @JavascriptInterface
        @Override
        public String getTrackString() {
            return urlDownloadToString(mVideoTrackUrl);
        }
    }
}
